/**
 * 抖音关注：程序员三丙
 * 知识星球：https://t.zsxq.com/j9b21
 */
package sanbing.example.dylike.infrastructure.gateway;

import com.github.benmanes.caffeine.cache.Cache;
import com.github.benmanes.caffeine.cache.Caffeine;
import jakarta.annotation.PostConstruct;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import sanbing.example.dylike.domain.SeckillGateway;

import java.time.Duration;
import java.util.UUID;
import java.util.concurrent.atomic.AtomicInteger;

@Component
@Slf4j
public class CaffeineSeckillGateway implements SeckillGateway {

    static final int INIT_CACHE_LIMIT = 100;

    final Cache<UUID, AtomicInteger> cache = Caffeine.newBuilder()
            .initialCapacity(INIT_CACHE_LIMIT)
            .maximumSize(INIT_CACHE_LIMIT)
            .expireAfterWrite(Duration.ofDays(1))
            .build();

    @PostConstruct
    public void init() {
        // 模拟初始化10个SKU，每个SKU 100个库存
        UUID[] skuList = new UUID[]{
                UUID.fromString("f6519f16-ca96-4518-9082-2c0002bfcfc4"),
                UUID.fromString("8de315f5-643b-4b8e-88f7-5cfd16c5d243"),
                UUID.fromString("cf62430e-57ed-477b-a077-9a64c9e8454e"),
                UUID.fromString("86c63137-18fc-4506-8c0c-6f9c6c2575d8"),
                UUID.fromString("860f770a-5ad0-4949-a2dd-527ce11ae905"),
                UUID.fromString("4dc8c321-ddeb-4c88-8039-e37d45a73490"),
                UUID.fromString("0c667579-96ec-477f-906c-05193078592b"),
                UUID.fromString("7d9968b2-a821-4aca-ae08-d85a7c9bd32b"),
                UUID.fromString("74a92771-1bc2-4b29-b607-f9fad62e72e1"),
                UUID.fromString("527abcf0-68b7-4a86-9677-18d1284f8379")
        };

        for (UUID skuId : skuList) {
            cache.put(skuId, new AtomicInteger(100));
        }
    }

    @Override
    public boolean write(UUID skuId) {
        // 实现秒杀逻辑，秒杀成功库存-1，不能超卖
        AtomicInteger stock = cache.getIfPresent(skuId);
        if (stock != null && stock.get() > 0) {
            int updatedStock = stock.decrementAndGet();
            if (updatedStock >= 0) {
                log.info("Seckill succeeded for SKU: {}, currentStock:{}", skuId, stock);
                return true;
            } else {
                stock.incrementAndGet(); // Rollback if decrement went below zero
            }
        }
        log.trace("Seckill failed for SKU: {}, currentStock:{}", skuId, stock);
        return false;
    }

    @Override
    public int read(UUID skuId) {
        // 查询当前库存
        AtomicInteger stock = cache.getIfPresent(skuId);
        int currentStock = (stock != null) ? stock.get() : 0;
        log.trace("Current stock for SKU {}: {}", skuId, currentStock);
        return currentStock;
    }


}